package com.itcast.googleplay.protocol;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import com.itcast.googleplay.http.HttpApi;
import com.itcast.googleplay.http.HttpHelper;
import com.itcast.googleplay.http.HttpHelper.HttpResult;
import com.itcast.googleplay.utils.IOUtils;
import com.itcast.googleplay.utils.UIUtils;
import android.text.TextUtils;

public abstract class BaseProtocol<T>{
	public T getData(String url,int index,String params){
		String data = getDataFromLocal(url,index,params);
		String json = null;
		if(!TextUtils.isEmpty(data)){
			//如果数据不为空,则赋给json
			json = data;
		}else{
			json = getDataFormNet(url,index,params);
		}
		
		if(!TextUtils.isEmpty(json)){
			return processData(json);
		}
		return null;
	}

	private String getDataFormNet(String url, int index,String params) {
		HttpHelper httpHelper = new HttpHelper();
		HttpResult httpResult = null;
		if(index==-1){
			httpResult = httpHelper.get(HttpApi.BASEURL+url+"?"+params);
		}else{
			httpResult = httpHelper.get(HttpApi.BASEURL+url+"?index="+index+params);
		}
		if(httpResult!=null){
			if(httpResult!=null){
				writeToLocal(httpResult.getString(), url, index,params);
				return httpResult.getString();
			}
		}
		return "";
	}

	private String getDataFromLocal(String url,int index,String params) {
		BufferedReader bufferedReader = null;
		try {
			File file = new File(UIUtils.getContext().getCacheDir(),url+index+params);
			bufferedReader = new BufferedReader(new FileReader(file.getAbsolutePath()));
			String lineOne = bufferedReader.readLine();
			Long invlideTime = Long.valueOf(lineOne);
			if(System.currentTimeMillis()<invlideTime){
				//数据有效
				StringBuffer stringBuffer = new StringBuffer();
				String line = "";
				while((line=bufferedReader.readLine())!=null){
					stringBuffer.append(line);
				}
				return stringBuffer.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			IOUtils.close(bufferedReader);
		}
		return "";
	}
	private void writeToLocal(String json,String url,int index,String params){
		BufferedWriter bufferedWriter = null;
		try {
			File file = new File(UIUtils.getContext().getCacheDir(),url+index+params);
			bufferedWriter = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
			bufferedWriter.write(System.currentTimeMillis()+30*60*1000+"\r\n");
			bufferedWriter.write(json.toCharArray());
			bufferedWriter.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			IOUtils.close(bufferedWriter);
		}
	}
	
	public abstract T processData(String json);
}
